package com.langyiquan.front.controller;

import com.langyiquan.bo.UserInfoBO;
import com.langyiquan.exception.http.ParamException;
import com.langyiquan.pojo.Users;
import com.langyiquan.service.ResourceService;
import com.langyiquan.service.UserService;
import com.langyiquan.utils.DateUtil;
import com.langyiquan.utils.UnifyResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Api(value = "用户中心", tags = {"用户中心相关接口"})
@RestController
@RequestMapping("user")
public class UserController extends BaseController{

    @Autowired
    private UserService userService;

    @Autowired
    private ResourceService resourceService;

    @ApiOperation(value = "获取用户信息",notes = "获取用户信息",httpMethod = "GET")
    @GetMapping("info")
    public UnifyResponse info(HttpServletRequest request){
        String userId = getPassportUserId(request);
        Users user = userService.queryUserInfo(userId);
        user.setPassword(null);
        return UnifyResponse.success(user);
    }


    @ApiOperation(value = "修改用户信息",notes = "修改用户信息",httpMethod = "POST")
    @PostMapping("update")
    public UnifyResponse update(@RequestBody @Valid UserInfoBO userInfoBO, BindingResult bindingResult, HttpServletRequest request){

        String userId = getPassportUserId(request);

        if(bindingResult.hasErrors()){
            Map<String,String> errorsMap = getBindingResultErrors(bindingResult);
            String errCode = errorsMap.entrySet().iterator().next().getValue();
            throw new ParamException(Integer.parseInt(errCode));
        }

        Users user = userService.updateUserInfo(userId,userInfoBO);

        return UnifyResponse.success(user);
    }


    @ApiOperation(value = "上传用户头像",notes = "上传用户头像",httpMethod = "POST")
    @PostMapping("uploadFace")
    public UnifyResponse uploadFace(MultipartFile file,@RequestParam String category, HttpServletRequest request){

        String userId = getPassportUserId(request);
        String avatarUrl = resourceService.uploadFile(file,category);
        userService.updateUserFace(userId,avatarUrl);
        Map<String,String> avatarMap = new HashMap<>();
        avatarMap.put("avatarUrl",avatarUrl+"?time="+ DateUtil.getCurrentDateString(DateUtil.DATE_PATTERN));
        return UnifyResponse.success(avatarMap);

    }


}
